package java8.parallel.demo01;

import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * @author ChangLiang
 * @date 2020/4/23
 */
public class LongAdder {

    public static long iterativeSum(long limit) {
        long result = 0L;
        for (long i = 1L; i < limit; i++) {
            result += i;
        }
        return result;
    }

    public static long streamIterateUsingSummingLong(long limit) {
        return Stream.iterate(0L, i -> i + 1).limit(limit).collect(Collectors.summingLong(i -> i));
    }

    public static long sequentialSum(long limit) {
        return Stream.iterate(0L, i -> i + 1).limit(limit).reduce(0L, Long::sum);
    }

    public static long parallelSum(long limit) {
        /// wrong way using parallel
//        return Stream.iterate(0L, i -> i + 1).parallel().limit(limit).reduce(0L, Long::sum);

        return Stream.iterate(0L, i -> i + 1).limit(limit).parallel().reduce(0L, Long::sum);
    }

    public static long streamIterateWithReduceByMapToLongAndParallel(long limit) {
        return Stream.iterate(0L, i -> i + 1).mapToLong(Long::longValue).parallel().limit(limit).reduce(0L, Long::sum);
    }

    public static long parallelRangedSum(long limit) {
        return LongStream.rangeClosed(1,limit).parallel().limit(limit).reduce(0L, Long::sum);
    }

    public static long rangedSum(long limit) {
        return LongStream.rangeClosed(1,limit).limit(limit).reduce(0L, Long::sum);
    }


}
